

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layuiAdmin 角色管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all">
</head>
<body>

  <div class="layui-fluid">   
    <div class="layui-card">
      <div class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">角色名</label>
            <div class="layui-input-block">
              <input type="text" name="rolename" placeholder="请输入" autocomplete="off" class="layui-input" id="rolename">
            </div>
          </div>
          <div class="layui-inline">
            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="role-search">
              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
            </button>
          </div>
        </div>
      </div>
      
      <div class="layui-card-body">
        <div style="padding-bottom: 10px;">
          <button class="layui-btn layuiadmin-btn-admin" data-type="batchdel">删除</button>
          <button class="layui-btn layuiadmin-btn-admin" data-type="add">添加</button>
        </div>
        
<!--        <table id="LAY-user-back-manage" lay-filter="LAY-user-back-manage"></table>-->
        <table id="role-manage" lay-filter="role-manage"></table>

        <script type="text/html" id="table-useradmin-admin">
          <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
          {{#  if(d.rolename == '超级管理员'){ }}
            <a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-delete"></i>删除</a>
          {{#  } else { }}
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
          {{#  } }}
        </script>
      </div>


    </div>
  </div>

 <script src="/layuiadmin/layui/layui.js"></script>
  <script>
  layui.config({
    base: '/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index', 'useradmin', 'table','tree'], function(){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table
    ,tree = layui.tree
    ,jsonData = [{
      "checked": false,
      "children": [{
        "checked": false,
        "children": [{
          "checked": false,
          "href": "/role/findData.do",
          "id": 8,
          "parentId": 2,
          "spread": "true",
          "title": "查看",
          "type": "按钮"
        }],
        "href": "/role/toRoleList.do",
        "id": 2,
        "parentId": 1,
        "spread": "true",
        "title": "角色管理",
        "type": "菜单"
      }, {
        "checked": false,
        "href": "/user/toUserList.do",
        "id": 7,
        "parentId": 1,
        "spread": "true",
        "title": "用户管理",
        "type": "菜单"
      }],
      "id": 1,
      "checked": false,
      "spread": false,
      "title": "用户",
      "type": "目录"
    }, {
      "checked": false,
      "id": 9,
      "spread": "true",
      "title": "控制台",
      "type": "目录"
    }];
    //方法级渲染
    table.render({
      elem: '#role-manage'
      ,url: '/role/findData.do'
      ,cols: [
        [
          {checkbox: true, fixed: true}
          ,{field:'rolename', title: '角色名'}
          ,{field:'descrption', title: '角色描述'}
          ,{field:'updateTime', title: '修改时间'}
          ,{field:'createTime', title: '创建时间'}
          ,{field:'ops', title:'操作',templet: '#table-useradmin-admin',width: 146}
        ]
      ]
      ,id: 'testReload'
      ,page: true
      ,height:'full-110'
    });

    //监听搜索
    form.on('submit(role-search)', function(data){
      var field = data.field;
      //执行重载(这里reload后面的ID是render后面的ID)
      table.reload('testReload', {
        where: {
          rolename: $("#rolename").val()
        },
        page: {
          curr: 1 //重新从第 1 页开始
      }
      });
    });
  
    //事件
    var active = {
      batchdel: function(){
        alert(111);
        var checkStatus = table.checkStatus('LAY-user-back-manage');
        alert(checkStatus.data);return false
        alert(checkData.length);
        if(checkData.length === 0){
          return layer.msg('请选择数据');
        }
        
        layer.prompt({
          formType: 1
          ,title: '敏感操作，请验证口令'
        }, function(value, index){
          layer.close(index);
          
          layer.confirm('确定删除吗？', function(index) {
            
            //执行 Ajax 后重载
            /*
            admin.req({
              url: 'xxx'
              //,……
            });
            */
            table.reload('LAY-user-back-manage');
            layer.msg('已删除');
          });
        }); 
      }
      ,add: function(){
        layer.open({
          //跳转页面是个隐藏div的时候用type=1，若是个地址的时候type=2
          type: 1
          ,title: '添加角色'
          ,content: $("#addRole")
          ,area : 'auto'
          ,success: function(){
            // 通过ajax获取后台所有的权限数据，然后在渲染到页面上
            $.ajax({
              url: '/role/getPermissionTree.do',
              type: 'GET',
              success: function (result) {
                if (result.ret == true) {
                  // 请求成功渲染权限树
                  tree.render({
                    elem: '#meun-tree'
                    ,data: result.data
                    ,showCheckbox: true  //是否显示复选框
                    ,id: 'meun-tree-demo'
                    ,isJump: false //是否允许点击节点时弹出新窗口跳转
                    ,click: function(obj){
                      var data = obj.data;  //获取当前点击的节点数据
                      layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                    }
                  });
                } else {
                  layer.msg(result.msg, {icon: 5});
                  layer.close(index);
                }
              },
              error: function (errorMsg) {
                layer.msg("数据异常!" + errorMsg, {icon: 5});
                layer.close(index);
                location.reload();
              },
            });
          }
          ,cancel : function() {
            // 你点击右上角 X 取消后要做什么
            $("#addRole")[0].reset();
            layui.form.render();
          }
        });
        // 监听提交按钮
        form.on('submit(addBtn)',function (data) {
          //获得选中的节点
          var checkData = tree.getChecked('meun-tree-demo');
          var list = new Array();
          list = getChecked_list(checkData);
          var field = data.field;
          // 向数据库添加数据
          $.ajax({
            url: '/role/add.do',
            type: 'POST',
            data: {"role":JSON.stringify(field),"ids":JSON.stringify(list)},
            success: function (result) {
              if (result.ret){
                //执行重载
                layer.msg('添加成功', {
                  offset: 'auto'
                  , icon: 1
                }, function () {
                  location.reload();
                });
              }else{
                layer.msg(result.msg,{icon: 5});
              }
            },
            error: function (errorMsg) {
              layer.msg("数据异常!" + errorMsg, {icon: 5});
            },
          });
          layer.closeAll(); //关闭弹层
          return false;
        })
      }
    }
    // 监听行工具事件使用该事件的时候要将按钮那里添加lay-event="edit",lay-event="del"
    table.on('tool(role-manage)', function (obj) {
      var data = obj.data;
      if (obj.event === 'del') {
        layer.confirm('真的删除吗！', function (index) {
          //异步像服务器发送删除请求
          $.ajax({
            url: '/role/del.do',
            type: 'POST',
            data: {'id': data.id},
            success: function (result) {
              if (result.ret == true) {
                layer.msg("删除成功!", {icon: 6});
                obj.del();
                layer.close(index);
              } else {
                layer.msg(result.msg, {icon: 5});
                layer.close(index);
              }
            },
            error: function (errorMsg) {
              layer.msg("数据异常!" + errorMsg, {icon: 5});
              layer.close(index);
              location.reload();
            },
          });
        });
        //更新用户
      } else if (obj.event == 'edit') {
        layer.open({
          type: 1,
          title: "更新用户",
          area: 'auto',
          content: $("#updateRole"),
          success: function () {
            // 通过ajax请求传递该角色ID然后查询出该角色下的权限
            $("#updateRole").find($("input[name='rolename']")).val(data.rolename);
            $("#updateRole").find($("textarea[name='descrption']")).val(data.descrption);
            $.ajax({
              url: '/role/getPermissionTree.do',
              type: 'GET',
              data: {'roleId': data.id},
              success: function (result) {
                if (result.ret == true) {
                  // 请求成功渲染权限树
                  tree.render({
                    elem: '#update-meun-tree'
                    ,data: result.data
                    ,showCheckbox: true  //是否显示复选框
                    ,id: 'update-meun-tree-demo'
                    ,isJump: false //是否允许点击节点时弹出新窗口跳转
                    ,click: function(obj){
                      var data = obj.data;  //获取当前点击的节点数据
                      layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                    }
                  });
                } else {
                  layer.msg(result.msg, {icon: 5});
                  layer.close(index);
                }
              },
              error: function (errorMsg) {
                layer.msg("数据异常!" + errorMsg, {icon: 5});
                layer.close(index);
                location.reload();
              },
            });
          }
          ,cancel : function() {
          // 你点击右上角 X 取消后要做什么
          $("#addRole")[0].reset();
          layui.form.render();
          }
        });
        updateData(data);
      }
    });


    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });

    function updateData(obj){
      form.on('submit(updateBtn)',function(data){
        var checkData = tree.getChecked('update-meun-tree-demo');
        var list = new Array();
        list = getChecked_list(checkData);
        var role = {
          id:obj.id,
          rolename:data.field.rolename,
          descrption:data.field.descrption
        }
        $.ajax({
          url: '/role/update.do',
          type: 'POST',
          data: {"role":JSON.stringify(role),"ids":JSON.stringify(list)},
          success: function (result) {
            if (result.ret){
              //执行重载
              layer.msg('修改成功',{
                icon: 6,
                time: 1000,
                end: function () {
                  location.reload();
                  layer.closeAll();//关闭所有的弹出层
                }
              })
            }else{
              layer.msg(result.msg,{icon: 5});
            }
          },
          error: function (errorMsg) {
            layer.msg("数据异常!" + errorMsg, {icon: 5});
            layer.closeAll();//关闭所有的弹出层
            location.reload();
          },
        });
        return false;
      });
    }
    // 获取选中节点的id
    function getChecked_list(data) {
      var id = "";
      $.each(data, function (index, item) {
        if (id != "") {
          id = id + "," + item.id;
        }
        else {
          id = item.id;
        }
        var i = getChecked_list(item.children);
        if (i != "") {
          id = id + "," + i;
        }
      });
      return id;
    }
  });
  </script>
</body>
<!--新增隐藏模块-->
<form class="layui-row" id="addRole" style="display: none">
  <div class="layui-form" lay-filter="layuiadmin-form-admin" id="layuiadmin-form-admin" style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">角色名</label>
      <div class="layui-input-inline">
        <input type="text" name="rolename" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">角色描述</label>
      <div class="layui-input-block">
        <textarea placeholder="请输入内容" class="layui-textarea" name="descrption"></textarea>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">菜单权限</label>
      <div class="layui-input-inline">
        <div id="meun-tree" class="demo-tree-more"></div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="addBtn">立即提交</button>
      </div>
    </div>
  </div>
</form>
<!-- 修改 start -->
<form class="layui-row" id="updateRole" style="display: none">
  <div class="layui-form" lay-filter="layuiadmin-form-admin"  style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
      <label class="layui-form-label">角色名</label>
      <div class="layui-input-inline">
        <input type="text" name="rolename" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">角色描述</label>
      <div class="layui-input-block">
        <textarea placeholder="请输入内容" class="layui-textarea" name="descrption"></textarea>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">菜单权限</label>
      <div class="layui-input-inline">
        <div id="update-meun-tree" class="demo-tree-more"></div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="updateBtn">立即提交</button>
      </div>
    </div>
  </div>
</form>
<!-- 修改end -->
</html>

